#include "dialog.h"
#include "ui_dialog.h"
#include "myframe.h"

#include <iostream>
using namespace std;

Dialog::Dialog(QWidget *parent):QDialog(parent),ui(new Ui::Dialog){

   /* QList<int> szamok;
    szamok.append(0);
    szamok.append(1);
    szamok.append(2);
    szamok.append(3);
    szamok.append(4);
    szamok.insert(0,7);
    cout<<"szamok"<<szamok[0]<<endl;
    cout<<"szamok"<<szamok[1]<<endl;*/


    ui->setupUi(this);

    path = QDir::currentPath();
    path.append("/source/images/");
    firstImage = 0;


    ui->imageFrame->setDraw(); //set to draw on imageFrame

    setPatternCategory();

    frameList.append(ui->imageFrameA);
    frameList.append(ui->imageFrameB);
    frameList.append(ui->imageFrameC);
    frameList.append(ui->imageFrameD);
    frameList.append(ui->imageFrameE);

    patternsFrame.append(ui->patternA);
    patternsFrame.append(ui->patternB);
    patternsFrame.append(ui->patternC);
    patternsFrame.append(ui->patternD);
    patternsFrame.append(ui->patternE);
    patternsFrame.append(ui->patternF);
    patternsFrame.append(ui->patternG);
    patternsFrame.append(ui->patternH);
    patternsFrame.append(ui->patternI);
    patternsFrame.append(ui->patternJ);
    patternsFrame.append(ui->patternK);
    patternsFrame.append(ui->patternL);


    QRegExp rx("\\d+");
    QRegExpValidator *validator = new QRegExpValidator(rx,NULL);
    ui->editHeight->setValidator(validator);
    ui->editWidth->setValidator(validator);

    ui->bakcground->setStyleSheet("border: 0px solid black");
    ui->imageFrame->setStyleSheet("background-color: rgb(200, 204, 212);border: 1px solid black;");
    ui->label->setStyleSheet("background-color: rgb(200, 204, 212);border: 1px solid black;");


    ui->arrowLeft->setStyleSheet("background:transparent;border:none");
    ui->arrowRight->setStyleSheet("background:transparent;border:none");
    ui->openButtonImage->setStyleSheet("background-color: rgb(200, 204, 212);border: 1px solid black;");
    ui->openButtonDir->setStyleSheet("background-color: rgb(200, 204, 212);border: 1px solid black;");


    connect(ui->arrowLeft, SIGNAL(mouseEntered()), this, SLOT(mouseEnteredLeft()));
    connect(ui->arrowRight, SIGNAL(mouseEntered()), this, SLOT(mouseEnteredRight()));
    connect(ui->arrowLeft, SIGNAL(mouseLeaved()), this, SLOT(mouseLeavedLeft()));
    connect(ui->arrowRight, SIGNAL(mouseLeaved()), this, SLOT(mouseLeavedRight()));
    connect(ui->arrowLeft, SIGNAL(mousePressed()), this, SLOT(mousePressedLeft()));
    connect(ui->arrowRight, SIGNAL(mousePressed()), this, SLOT(mousePressedRight()));
    connect(ui->openButtonImage, SIGNAL(mousePressed()), this, SLOT(mousePressedOpenImage()));
    connect(ui->openButtonDir, SIGNAL(mousePressed()), this, SLOT(mousePressedOpenDir()));
    connect(ui->removeButtonA, SIGNAL(mousePressed()), this, SLOT(mousePressedRemoveA()));
    connect(ui->removeButtonB, SIGNAL(mousePressed()), this, SLOT(mousePressedRemoveB()));
    connect(ui->removeButtonC, SIGNAL(mousePressed()), this, SLOT(mousePressedRemoveC()));
    connect(ui->removeButtonD, SIGNAL(mousePressed()), this, SLOT(mousePressedRemoveD()));
    connect(ui->removeButtonE, SIGNAL(mousePressed()), this, SLOT(mousePressedRemoveE()));


    connect(ui->imageFrameA, SIGNAL(mousePressed()), this, SLOT(mousePressedA()));
    connect(ui->imageFrameA, SIGNAL(mouseEntered()), this, SLOT(mouseEnteredA()));
    connect(ui->imageFrameA, SIGNAL(mouseLeaved()), this, SLOT(mouseLeavedA()));
    connect(ui->imageFrameB, SIGNAL(mousePressed()), this, SLOT(mousePressedB()));
    connect(ui->imageFrameB, SIGNAL(mouseEntered()), this, SLOT(mouseEnteredB()));
    connect(ui->imageFrameB, SIGNAL(mouseLeaved()), this, SLOT(mouseLeavedB()));
    connect(ui->imageFrameC, SIGNAL(mousePressed()), this, SLOT(mousePressedC()));
    connect(ui->imageFrameC, SIGNAL(mouseEntered()), this, SLOT(mouseEnteredC()));
    connect(ui->imageFrameC, SIGNAL(mouseLeaved()), this, SLOT(mouseLeavedC()));
    connect(ui->imageFrameD, SIGNAL(mousePressed()), this, SLOT(mousePressedD()));
    connect(ui->imageFrameD, SIGNAL(mouseEntered()), this, SLOT(mouseEnteredD()));
    connect(ui->imageFrameD, SIGNAL(mouseLeaved()), this, SLOT(mouseLeavedD()));
    connect(ui->imageFrameE, SIGNAL(mousePressed()), this, SLOT(mousePressedE()));
    connect(ui->imageFrameE, SIGNAL(mouseEntered()), this, SLOT(mouseEnteredE()));
    connect(ui->imageFrameE, SIGNAL(mouseLeaved()), this, SLOT(mouseLeavedE()));

    connect(ui->imageFrame, SIGNAL(mousePressed()), this, SLOT(mousePressedImage()));
    connect(ui->imageFrame, SIGNAL(mouseExit()), this, SLOT(mouseReleaseImage()));
    connect(ui->imageFrame, SIGNAL(mouseOn()), this, SLOT(mouseMovingImage()));

//Patterns arrows
    connect(ui->patternFrameUp, SIGNAL(mouseEntered()), this, SLOT(mousePatternEnteredUp()));
    connect(ui->patternFrameDown, SIGNAL(mouseEntered()), this, SLOT(mousePatternEnteredDown()));
    connect(ui->patternFrameUp, SIGNAL(mouseLeaved()), this, SLOT(mousePatternLeavedUp()));
    connect(ui->patternFrameDown, SIGNAL(mouseLeaved()), this, SLOT(mousePatternLeavedDown()));
    connect(ui->patternFrameUp, SIGNAL(mousePressed()), this, SLOT(mousePatternPressedUp()));
    connect(ui->patternFrameDown, SIGNAL(mousePressed()), this, SLOT(mousePatternPressedDown()));

//Start button
    connect(ui->startButton, SIGNAL(mousePressed()), this, SLOT(mouseButtonStart()));

//open all category
    fillPattern();

}

Dialog::~Dialog()
{
    delete ui;
}

QString Dialog::getPath(){
    return path;
}

void Dialog::mousePressedA()
{
    loadMainFrame(0);
}

void Dialog::mouseEnteredA()
{
    ui->imageFrameA->setStyleSheet("background-color: rgb(200, 204, 212);border: 2px solid black;");
}

void Dialog::mouseLeavedA()
{
    ui->imageFrameA->setStyleSheet("background-color: rgb(200, 204, 212);border: 1px solid black;");
}

void Dialog::mousePressedB()
{
    loadMainFrame(1);
}

void Dialog::mouseEnteredB()
{
    ui->imageFrameB->setStyleSheet("background-color: rgb(200, 204, 212);border: 2px solid black;");
}

void Dialog::mouseLeavedB()
{
    ui->imageFrameB->setStyleSheet("background-color: rgb(200, 204, 212);border: 1px solid black;");
}

void Dialog::mousePressedC()
{
    loadMainFrame(2);
}

void Dialog::mouseEnteredC()
{
    ui->imageFrameC->setStyleSheet("background-color: rgb(200, 204, 212);border: 2px solid black;");
}

void Dialog::mouseLeavedC()
{
    ui->imageFrameC->setStyleSheet("background-color: rgb(200, 204, 212);border: 1px solid black;");
}

void Dialog::mousePressedD()
{
    loadMainFrame(3);
}

void Dialog::mouseEnteredD()
{
    ui->imageFrameD->setStyleSheet("background-color: rgb(200, 204, 212);border: 2px solid black;");
}

void Dialog::mouseLeavedD()
{
    ui->imageFrameD->setStyleSheet("background-color: rgb(200, 204, 212);border: 1px solid black;");
}

void Dialog::mousePressedE()
{
    loadMainFrame(4);
}

void Dialog::mouseEnteredE()
{
    ui->imageFrameE->setStyleSheet("background-color: rgb(200, 204, 212);border: 2px solid black;");
}

void Dialog::mouseLeavedE()
{
    ui->imageFrameE->setStyleSheet("background-color: rgb(200, 204, 212);border: 1px solid black;");
}

void Dialog::mouseEnteredLeft(){
    QImage img = QImage(path + "arrow_left.png");
    ui->arrowLeft->setBackgroundImage(img);
}

void Dialog::mouseEnteredRight(){
    QImage img = QImage(path + "arrow_right.png");
    ui->arrowRight->setBackgroundImage(img);
}

void Dialog::mouseLeavedLeft(){
    ui->arrowLeft->removeBackgroundImage();
}

void Dialog::mouseLeavedRight(){
    ui->arrowRight->removeBackgroundImage();
}

void Dialog::mousePressedOpenImage(){
    QString string = openImage();
    imagesPath.append(string);
    QImage img = QImage(string);
    ui->imageFrame->setBackgroundImage(img);
    if (imagesPath.size()>5){
        firstImage = imagesPath.size() - 5;
        for (int i = 0;i<5;i++){
            imagesList.removeFirst();
        }
        for (int i = firstImage;i < imagesPath.size();i++){
            imagesList.append(QImage(imagesPath[i]));
        }
    }
    else
        imagesList.append(img);
    showImages();
}

void Dialog::mousePressedOpenDir(){
    QString folderPath = openFolder();
    QDir myDir(folderPath);
    QStringList nameFilter;
    nameFilter<<"*.png"<<"*.jpg"<<"*.gif"<<"*.jpeg";
    QStringList list = myDir.entryList(nameFilter, QDir::Files);
    if (!imagesList.empty())
        imagesList.clear();
    for (int i = 0; i < list.size(); ++i){
        imagesPath.append(folderPath + "/" + list.at(i));
    }
    if(imagesPath.size() > 5){
       firstImage = imagesPath.size() - 5;
    }
    else{
       firstImage = 0;
    }
    for(int i = firstImage; i < imagesPath.size(); i++){
        imagesList.append(QImage(imagesPath[i]));
    }
    loadMainFrame(0);
    showImages();
}
void Dialog::loadMainFrame(int index){
    if ((firstImage + index) < (imagesPath.size())){
        ui->imageFrame->setBackgroundImage(imagesList[index]);
        loadSearchResult(imagesPath[firstImage + index]);
    }
}


void Dialog::removeImage(int index){
    if ((firstImage + index) < (imagesPath.size())){
        imagesPath.removeOne(imagesPath[index + firstImage]);
        imagesList.removeOne(imagesList[index]);
        if (imagesPath.size()<5){
           frameList[imagesList.size()]->removeBackgroundImage();
        }
        else{
            if ((firstImage + 4) < imagesPath.size()) {
                imagesList.append(QImage(imagesPath[firstImage + 4]));
            }
            else{
                firstImage--;
                imagesList.insert(0,QImage(imagesPath[firstImage]));
            }
        }
        showImages();
    }
}
void Dialog::mousePressedRemoveA(){
    removeImage(0);

}
void Dialog::mousePressedRemoveB(){
    removeImage(1);
}
void Dialog::mousePressedRemoveC(){
    removeImage(2);
}
void Dialog::mousePressedRemoveD(){
  removeImage(3);
}
void Dialog::mousePressedRemoveE(){
    removeImage(4);
}

void Dialog::mousePressedImage(){
    startX = ui->imageFrame->x;
    startY = ui->imageFrame->y;
    ui->imageFrame->setPositions(startX, startY, ui->imageFrame->x - startX, ui->imageFrame->y - startY, ui->editWidth, ui->editHeight);
}

void Dialog::mousePressedLeft(){
    if ((firstImage != 0) && (imagesPath.size() >= 5)){
        firstImage--;
        imagesList.removeLast();
        imagesList.insert(0,QImage(imagesPath[firstImage]));
        showImages();
    }
}
void Dialog::mousePressedRight(){
    if (((firstImage + 4) < imagesPath.size() - 1) && (imagesPath.size() >= 5)){
        firstImage++;
        imagesList.removeFirst();
        imagesList.append(QImage(imagesPath[firstImage + 4]));
        showImages();
    }
}

void Dialog::mouseReleaseImage(){
    ui->imageFrame->setPositions(startX, startY, ui->imageFrame->x - startX, ui->imageFrame->y - startY, ui->editWidth, ui->editHeight);
}

void Dialog::mouseMovingImage(){
    endX = ui->imageFrame->x;
    endY = ui->imageFrame->y;
    ui->imageFrame->setPositions(startX, startY, endX - startX, endY - startY, ui->editWidth, ui->editHeight);
}


void Dialog::showImages(){
    if (imagesPath.size()<5){
        for (int i=0;i<imagesPath.size();i++){
            frameList[i]->setBackgroundImage(imagesList[i]);
        }
    }
    else
        for (int i=0;i<5;i++){
            frameList[i]->setBackgroundImage(imagesList[i]);
        }
}
//Pattern arrows Up/Down

void Dialog::mousePatternEnteredUp(){
    QImage img = QImage(path + "arrow_up.png");
    ui->patternFrameUp->setBackgroundImage(img);
}

void Dialog::mousePatternEnteredDown(){
    QImage img = QImage(path + "arrow_down.png");
    ui->patternFrameDown->setBackgroundImage(img);
}

void Dialog::mousePatternLeavedUp(){
    ui->patternFrameUp->removeBackgroundImage();
}

void Dialog::mousePatternLeavedDown(){
    ui->patternFrameDown->removeBackgroundImage();
}

//up-down button
void Dialog::mousePatternPressedUp(){
    int loop = 0;
    while(loop < 11){
        if(actualPattern > 0){
            --actualPattern;
            setPatternFrames();
            for(int i = 0; i < 12; ++i){
                patternsFrame[i]->setBackgroundImage(QImage(patternsPath[i + actualPattern]));
                if(category[i + actualPattern]){
                    patternsFrame[i]->setStyleSheet("border: 2px solid red;");
                }
            }
        }
        Sleeper::msleep(1);
        ++loop;
    }
}

void Dialog::mousePatternPressedDown(){
    int loop = 0;
    while(loop < 11){
        if((actualPattern + 12) < numberOfPatterns){
            ++actualPattern;
            setPatternFrames();
            for(int i = 0; i < 12; ++i){
                patternsFrame[i]->setBackgroundImage(QImage(patternsPath[i + actualPattern]));
                if(category[i + actualPattern]){
                    patternsFrame[i]->setStyleSheet("border: 2px solid red;");
                }
            }
        }
        Sleeper::msleep(1);
        ++loop;
    }
}

//search image in search_result file
QStringList Dialog::getImageInformation(QString name){
    QFile file(QDir::currentPath() + "/source/img_datas/search_result");
    if(!file.open(QIODevice::ReadOnly)) {
        ui->label->setText("Hiba!");
    }

    QTextStream in(&file);

    while(!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(">");
        if(!name.compare(fields[0])){
            file.close();
            return fields;
        }
    }

    file.close();
    return QStringList();
}

void Dialog::loadSearchResult(QString name){
    QStringList list = getImageInformation(name);
    if(!list.isEmpty()){
        for(int i = 0; i < 100; ++i){
            category[i] = false;
        }
        int **searchResults = new int*[list.size() - 1];
        for(int i = 1; i < list.size(); ++i){
            searchResults[i - 1] = new int[4];
            QStringList numbers = list.at(i).split("-");
            category[numbers.at(0).toInt()] = true;
            for(int j = 1; j < 5; ++j){
                searchResults[i - 1][j - 1] = numbers.at(j).toInt();
            }
        }
        ui->imageFrame->drawSearchresult(searchResults, list.size() - 1);
        delete [] searchResults;
    }
    else{
        ui->label->setText("Ehhez a képhez nincs információ!");
    }
}

//saving new match to the config file
void Dialog::saveNewMatch(QString name, int category, int width, int height, int lWidth, int lHeight){
    QFile file(QDir::currentPath() + "/source/img_datas/search_result");
    if(!file.open(QIODevice::ReadOnly)) {
        ui->label->setText("Hiba!");
    }

    QFile ofile(QDir::currentPath() + "/source/img_datas/search_result_cache");
    if(!ofile.open(QIODevice::WriteOnly)) {
        ui->label->setText("Hiba!");
    }

    QTextStream in(&file);
    QTextStream out(&ofile);

    bool nothing = true;
    while(!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(">");
        if(!name.compare(fields[0])){
            nothing = false;
            out<<line<<">"<<category<<"-"<<width<<"-"<<height<<"-"<<lWidth<<"-"<<lHeight;
        }
        else{
            out<<line;
        }
    }
    if(nothing){
        out<<name<<">"<<category<<"-"<<width<<"-"<<height<<"-"<<lWidth<<"-"<<lHeight;
    }

    file.close();
    QFile::remove(QDir::currentPath() + "/source/img_datas/search_result");
    ofile.rename("search_result");
    ofile.close();
}

//button start listener
void Dialog::mouseButtonStart(){
    category[5] = true;
    category[10] = true;
    category[15] = true;
    fillPattern();
}

//loading patterns
void Dialog::fillPattern(){
    actualPattern = 0;
    QDir myDir(QDir::currentPath() + "/source/class/");
    QStringList nameFilter;
    nameFilter<<"*.png"<<"*.ppm";
    QStringList list = myDir.entryList(nameFilter, QDir::Files);
    for(int i = 0; i < list.size(); ++i){
        patternsPath.append(QDir::currentPath() + "/source/class/" + list.at(i));
    }
    numberOfPatterns = list.size();
    int length = 12;
    if(list.size() < 12){
        length = list.size();
    }
    for(int i = 0; i < length; ++i){
        patternsFrame[i]->setBackgroundImage(QImage(patternsPath[i]));
        if(category[i]){
            patternsFrame[i]->setStyleSheet("border: 2px solid red;");
        }
    }
}

void Dialog::setPatternCategory(){
    for(int i = 0; i < 100; ++i){
        category[i] = false;
    }
}

void Dialog::setPatternFrames(){
    for(int i = 0; i < 12; ++i){
        patternsFrame[i]->setStyleSheet("border: 1px solid black;");
    }
}

//add new images to list, returns his paths
QString Dialog::openImage(){
    return QFileDialog::getOpenFileName(this, tr("Open File"), "C:/", tr("Images (*.png *.xpm *.jpg *.jpeg)"));
}

QString Dialog::openFolder(){
    QFileDialog dialog;
    dialog.setFileMode(QFileDialog::Directory);
    dialog.setOption(QFileDialog::ShowDirsOnly);
    return dialog.getExistingDirectory(this, tr("Open Directory"));
}
